package com.dotstone.chipism.activity;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Scene;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ShareManager;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BlurBehind;
import com.dotstone.chipism.view.OnBlurCompleteListener;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AuthorConfirmActivity extends BaseActivity {
	private LinearLayout mBackL;
	private Button mNextBtn;
	private EditText mAuthorEd;
	private LinearLayout mTimeL;
	private TextView mTimeTv;
	private TextView tv_statusBar_mian;
	private int timelimit = -1;
	private SVProgressHUD mSVProgressHUD;
	private TextView mTransferTv;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.nextstep:
			// 判断名称是否符合
			// 判断时间是否设置
			// 获取分享的场景和设备
			// 判断是否为0 如果不为0 则遍历 获取sceneId 和deviceId
			String name = mAuthorEd.getText().toString();
			if (name.length() < 2 || name.length() > 8) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.share_name_length));
				return;
			}

			if (timelimit < 0) {
				ToastShow.Show(getApplicationContext(),
						getString(R.string.share_limit));
				return;
			}
			List<Scene> scenes = ShareManager.getInstance().getmScenes();
			List<Device> devices = ShareManager.getInstance().getmDevices();
			String sceneIds = "";
			String deviceIds = "";
			for (int i = 0; i < scenes.size(); i++) {
				if (i != scenes.size() - 1) {
					sceneIds += scenes.get(i).getSceneId() + ",";
				} else {
					sceneIds += scenes.get(i).getSceneId();
				}
			}
			if (sceneIds.equals("")) {
				sceneIds = "0";
			}
			for (int i = 0; i < devices.size(); i++) {
				if (i != devices.size() - 1) {
					deviceIds += devices.get(i).getDeviceID() + ",";
				} else {
					deviceIds += devices.get(i).getDeviceID();
				}
			}
			if (deviceIds.equals("")) {
				deviceIds = "0";
			}
			mSVProgressHUD = new SVProgressHUD(this);
			mSVProgressHUD.showWithStatus("正在提交");
			upLoadShare(name, sceneIds, deviceIds);
			break;
		case R.id.time_layout:
			if (ShareManager.getInstance().getShareType() != 3) {
				return;
			}
			BlurBehind.getInstance().execute(MainActivity.mainActivity,
					new OnBlurCompleteListener() {
						@Override
						public void onBlurComplete() {
							Intent intent = new Intent(
									AuthorConfirmActivity.this,
									TimeSettingActivity2.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
							startActivityForResult(intent, 0);
						}
					});
			break;

		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_authority_confirm;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		BlurBehind.getInstance().setBackground(this);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		mBackL = $(R.id.back_layout);
		mNextBtn = $(R.id.nextstep);
		mNextBtn.setText(getString(R.string.confirm_author1));
		mNextBtn.setVisibility(View.VISIBLE);
		mAuthorEd = $(R.id.author_ed);
		mTimeL = $(R.id.time_layout);
		mTimeTv = $(R.id.time_tv);
		mTransferTv = $(R.id.transfer_tv);
		mBackL.setOnClickListener(this);
		mNextBtn.setOnClickListener(this);
		mTimeL.setOnClickListener(this);
		if (ShareManager.getInstance().getShareType() == 1) {
			mTimeL.setVisibility(View.GONE);
			timelimit = 0;
		} else if (ShareManager.getInstance().getShareType() == 2) {
			mTimeL.setVisibility(View.GONE);
			timelimit = 4;
		} else if (ShareManager.getInstance().getShareType() == 3) {
			mTimeL.setVisibility(View.VISIBLE);
			timelimit = 0;
		} else if (ShareManager.getInstance().getShareType() == 4) {
			mTimeL.setVisibility(View.GONE);
			timelimit = 0;
			mTransferTv.setVisibility(View.VISIBLE);
		}
		boolVersion();
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);
		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// 根据上面发送过去的请求吗来区别
		switch (requestCode) {
		case 0:
			boolean now = intent.getBooleanExtra("now", false);
			boolean cancel = intent.getBooleanExtra("cancel", false);
			if (cancel) {
				return;
			}
			if (!now) {
				String year = intent.getStringExtra("year");
				String month = intent.getStringExtra("month");
				String day = intent.getStringExtra("day");
				String time = "";
				if (!year.equals("0")) {
					time += year + "年";
					timelimit += Integer.parseInt(year) * 365 * 24;
				}
				if (!month.equals("0")) {
					time += month + "月";
					timelimit += Integer.parseInt(month) * 30 * 24;
				}
				if (!day.equals("0")) {
					time += day + "日 ";
					timelimit += Integer.parseInt(day) * 24;
				}
				mTimeTv.setText(time);
			} else {

			}
			break;

		default:
			break;
		}
	}

	private void upLoadShare(String name, String sceneIds, String deviceIds) {
		RequestParams params = new RequestParams(HttpURL.ADD_SHARE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			if (!deviceIds.equals("0")) {
				obj.put("deviceIds", deviceIds);
			}
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("invalidHour", timelimit + "");
			obj.put("shareType", ShareManager.getInstance().getShareType());
			if (!sceneIds.equals("0")) {
				obj.put("sceneIds", sceneIds);
			}
			obj.put("shareRemarks", name);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token",
					(String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload Share = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.i("wmy", result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						
						final String shareInfoId = jo.getString("data");
						BlurBehind.getInstance().execute(
								MainActivity.mainActivity,
								new OnBlurCompleteListener() {
									@Override
									public void onBlurComplete() {
										Intent intent = new Intent(
												AuthorConfirmActivity.this,
												QrcodeActivity.class);
										intent.putExtra("shareInfoId",
												shareInfoId);
										intent.putExtra("shareInfoUserId", SocketManager.getInstance().user_id);
										intent.putExtra("entry", 2);// type是分享
										intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
										startActivity(intent);
										finish();
									}
								});

					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "申请授权失败！");
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				ToastShow.Show(getApplicationContext(), "网络错误！");
			}

			@Override
			public void onFinished() {

			}

		});
	}

}
